"""
使用PaddleHub的transformer-tiny-en2zh模型的翻译服务器
"""

from flask import Flask, request, jsonify
from flask_cors import CORS
import paddlehub as hub

app = Flask(__name__)
CORS(app)

# 加载翻译模型
model = hub.Module(name='transformer-tiny-en2zh')

@app.route('/translate', methods=['POST'])
def translate():
    """
    翻译API端点
    """
    try:
        data = request.json
        text = data.get('text', '')
        
        if not text:
            return jsonify({'error': '文本为空'}), 400
        
        # 如果文本太长，截取前1000个字符
        if len(text) > 1000:
            text = text[:1000]
        
        # 使用PaddleHub模型进行翻译
        result = model.translate([text])
        translation = result[0] if result else '翻译失败'
        
        return jsonify({'translation': translation})
    
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/health', methods=['GET'])
def health():
    """
    健康检查端点
    """
    return jsonify({
        'status': 'ready',
        'model': 'transformer-tiny-en2zh'
    })

if __name__ == '__main__':
    print("=" * 60)
    print("PaddleHub transformer-tiny-en2zh 翻译服务器启动中...")
    print("=" * 60)
    print("\n✓ 模型已加载")
    print("\n服务器地址: http://localhost:5000")
    print("翻译接口: POST http://localhost:5000/translate")
    print("健康检查: GET http://localhost:5000/health")
    print("\n按 Ctrl+C 停止服务器")
    print("=" * 60)
    
    app.run(host='0.0.0.0', port=5000, debug=False)